using System;
using System.IO;
using UnityEngine;
using UnityEngine.Recorder;

namespace UTJ.FrameCapturer.Recorders
{
	[Recorder(typeof(WEBMRecorderSettings), "Video", "UTJ/Legacy/WebM")]
	[Obsolete("'UTJ/WEBM' is obsolete, concider using 'Unity/Movie' instead", false)]
	public class WEBMRecorder : GenericRecorder<WEBMRecorderSettings>
	{
		private fcAPI.fcWebMContext m_ctx;

		private fcAPI.fcStream m_stream;

		public override bool BeginRecording(RecordingSession session)
		{
			if (!base.BeginRecording(session))
			{
				return false;
			}
			m_Settings.m_DestinationPath.CreateDirectory();
			return true;
		}

		public override void EndRecording(RecordingSession session)
		{
			m_ctx.Release();
			m_stream.Release();
			base.EndRecording(session);
		}

		public override void RecordFrame(RecordingSession session)
		{
			if (m_Inputs.Count != 1)
			{
				throw new Exception("Unsupported number of sources");
			}
			BaseRenderTextureInput baseRenderTextureInput = (BaseRenderTextureInput)m_Inputs[0];
			RenderTexture outputRT = baseRenderTextureInput.outputRT;
			if (!m_ctx)
			{
				fcAPI.fcWebMConfig conf = m_Settings.m_WebmEncoderSettings;
				conf.video = true;
				conf.audio = false;
				conf.videoWidth = outputRT.width;
				conf.videoHeight = outputRT.height;
				if (m_Settings.m_AutoSelectBR)
				{
					conf.videoTargetBitrate = (int)(((double)(outputRT.width * outputRT.height) / 1000.0 / 245.0 + 1.16) * ((double)conf.videoTargetFramerate / 48.0 + 0.5) * 1000000.0);
				}
				conf.videoTargetFramerate = (int)Math.Ceiling(m_Settings.m_FrameRate);
				m_ctx = fcAPI.fcWebMCreateContext(ref conf);
				string path = m_Settings.m_BaseFileName.BuildFileName(session, base.recordedFramesCount, conf.videoWidth, conf.videoHeight, "webm");
				string path2 = Path.Combine(m_Settings.m_DestinationPath.GetFullPath(), path);
				m_stream = fcAPI.fcCreateFileStream(path2);
				fcAPI.fcWebMAddOutputStream(m_ctx, m_stream);
			}
			fcAPI.fcLock(outputRT, TextureFormat.RGB24, delegate(byte[] data, fcAPI.fcPixelFormat fmt)
			{
				fcAPI.fcWebMAddVideoFramePixels(m_ctx, data, fmt, session.recorderTime);
			});
		}
	}
}
